package de.duester.genealogy.model.dao;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import de.duester.genealogy.model.Event;
import de.duester.genealogy.model.Place;

import de.duester.genealogy.model.EventPlace;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table EVENT_PLACE.
*/
public class EventPlaceDao extends AbstractDao<EventPlace, Long> {

    public static final String TABLENAME = "EVENT_PLACE";

    /**
     * Properties of entity EventPlace.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property EventId = new Property(1, Long.class, "eventId", false, "EVENT_ID");
        public final static Property PlaceId = new Property(2, Long.class, "placeId", false, "PLACE_ID");
        public final static Property RoleCode = new Property(3, String.class, "roleCode", false, "ROLE_CODE");
    };

    private DaoSession daoSession;

    private Query<EventPlace> event_EventPlacesQuery;
    private Query<EventPlace> place_EventPlacesQuery;

    public EventPlaceDao(DaoConfig config) {
        super(config);
    }
    
    public EventPlaceDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'EVENT_PLACE' (" + //
                "'_id' INTEGER PRIMARY KEY ," + // 0: id
                "'EVENT_ID' INTEGER," + // 1: eventId
                "'PLACE_ID' INTEGER," + // 2: placeId
                "'ROLE_CODE' TEXT);"); // 3: roleCode
        // Add Indexes
        db.execSQL("CREATE UNIQUE INDEX " + constraint + "IDX_EVENT_PLACE_EVENT_ID_PLACE_ID_ROLE_CODE ON EVENT_PLACE" +
                " (EVENT_ID,PLACE_ID,ROLE_CODE);");
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'EVENT_PLACE'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, EventPlace entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
 
        Long eventId = entity.getEventId();
        if (eventId != null) {
            stmt.bindLong(2, eventId);
        }
 
        Long placeId = entity.getPlaceId();
        if (placeId != null) {
            stmt.bindLong(3, placeId);
        }
 
        String roleCode = entity.getRoleCode();
        if (roleCode != null) {
            stmt.bindString(4, roleCode);
        }
    }

    @Override
    protected void attachEntity(EventPlace entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public EventPlace readEntity(Cursor cursor, int offset) {
        EventPlace entity = new EventPlace( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1), // eventId
            cursor.isNull(offset + 2) ? null : cursor.getLong(offset + 2), // placeId
            cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // roleCode
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, EventPlace entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setEventId(cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1));
        entity.setPlaceId(cursor.isNull(offset + 2) ? null : cursor.getLong(offset + 2));
        entity.setRoleCode(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(EventPlace entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(EventPlace entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "eventPlaces" to-many relationship of Event. */
    public List<EventPlace> _queryEvent_EventPlaces(Long eventId) {
        synchronized (this) {
            if (event_EventPlacesQuery == null) {
                QueryBuilder<EventPlace> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.EventId.eq(null));
                event_EventPlacesQuery = queryBuilder.build();
            }
        }
        Query<EventPlace> query = event_EventPlacesQuery.forCurrentThread();
        query.setParameter(0, eventId);
        return query.list();
    }

    /** Internal query to resolve the "eventPlaces" to-many relationship of Place. */
    public List<EventPlace> _queryPlace_EventPlaces(Long placeId) {
        synchronized (this) {
            if (place_EventPlacesQuery == null) {
                QueryBuilder<EventPlace> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.PlaceId.eq(null));
                place_EventPlacesQuery = queryBuilder.build();
            }
        }
        Query<EventPlace> query = place_EventPlacesQuery.forCurrentThread();
        query.setParameter(0, placeId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getEventDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T1", daoSession.getPlaceDao().getAllColumns());
            builder.append(" FROM EVENT_PLACE T");
            builder.append(" LEFT JOIN EVENT T0 ON T.'EVENT_ID'=T0.'_id'");
            builder.append(" LEFT JOIN PLACE T1 ON T.'PLACE_ID'=T1.'_id'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected EventPlace loadCurrentDeep(Cursor cursor, boolean lock) {
        EventPlace entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        Event event = loadCurrentOther(daoSession.getEventDao(), cursor, offset);
        entity.setEvent(event);
        offset += daoSession.getEventDao().getAllColumns().length;

        Place place = loadCurrentOther(daoSession.getPlaceDao(), cursor, offset);
        entity.setPlace(place);

        return entity;    
    }

    public EventPlace loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<EventPlace> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<EventPlace> list = new ArrayList<EventPlace>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<EventPlace> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<EventPlace> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
